﻿using SuperX.Common.Log;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using System;
using System.IO;

namespace SuperX.SuperSocket.Socket.Transfer.Server.UpLoad.Command
{
    public class DoUpLoad : CommandBase<TransferSession, BinaryRequestInfo>
    {
        public override string Name => "DoUpLoad";

        public override void ExecuteCommand(TransferSession session, BinaryRequestInfo requestInfo)
        {
            try
            {
                FileInfo ClientConfigInfo = SerializeHelp.Deserialize<FileInfo>(requestInfo.Body);
                string saveName = Path.GetFullPath(ClientConfigInfo.SaveName);
                if (!session.TransferServer.ServerUploadState.GetLock(session.SessionID, session.RemoteEndPoint.Address.ToString()))
                {
                    //获得上传锁不成功
                    //代表有其他客户端正在执行上传文件到服务器的命令，则向客户端发出提示，并返回
                    session.TransferServer.ServerUploadState.CheckUploadType = CheckUploadType.Uploading;
                    byte[] data = SerializeHelp.Serialize(session.TransferServer.ServerUploadState);
                    session.FileTransferEngine.SendData(UpLoadOP.DoExists, data, 0, data.Length);
                    session.FileTransferEngine.Dispose();
                    return;
                }

                if (File.Exists(saveName))
                {
                    session.TransferServer.ServerUploadState.CheckUploadType = CheckUploadType.FileExists;
                    byte[] data = SerializeHelp.Serialize(session.TransferServer.ServerUploadState);
                    session.FileTransferEngine.SendData(UpLoadOP.DoExists, data, 0, data.Length);
                    //session.FileTransferEngine.SendData(UpLoadOP.DoExists, new byte[] { 1 }, 0, 1);
                    return;
                }
                session.FileTransferEngine.OnStartTransfer(ClientConfigInfo);
                session.FileTransferEngine.DoUpLoad(ClientConfigInfo);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);
            }
        }
    }
}